package com.qlmjx.sevalopos;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.display.DisplayManager;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.qlmjx.sevalopos.Bean.ErW;
import com.qlmjx.sevalopos.Bean.ManageOrderInfo;
import com.qlmjx.sevalopos.Bean.ManageUpaidInfo;
import com.qlmjx.sevalopos.Bean.OrederBean;
import com.qlmjx.sevalopos.Bean.UpaidBean;
import com.qlmjx.sevalopos.View.BaseDialog;
import com.qlmjx.sevalopos.View.ComfirmPay2Dialog;
import com.qlmjx.sevalopos.View.ComfirmPayDialog;
import com.qlmjx.sevalopos.View.NoScrollingListView;
import com.qlmjx.sevalopos.adapter.OrderDetailAdapter;
import com.qlmjx.sevalopos.adapter.UnpaidAdapter;
import com.qlmjx.sevalopos.base.BaseActivity;
import com.qlmjx.sevalopos.base.BaseEvent;
import com.qlmjx.sevalopos.event.PaySEvent;
import com.qlmjx.sevalopos.event.PaystatrEvent;
import com.qlmjx.sevalopos.event.UnpaidCustomerShopEvent;
import com.qlmjx.sevalopos.event.UnpaidEvent;
import com.qlmjx.sevalopos.https.HttpAddress;
import com.qlmjx.sevalopos.https.RequestParams;
import com.qlmjx.sevalopos.utils.ConstantsUtils;
import com.universal.frame.generalutils.GeneralUtil;
import com.universal.frame.generalutils.JsonUtil;
import com.universal.frame.generalutils.SharedPreferencesUtil;
import com.universal.frame.generalutils.ToastUtil;
import com.universal.frame.okhttp.OKHttpUtils;
import com.universal.frame.okhttp.ResultCallBack;
import com.universal.frame.pulltorefresh.PullToRefreshBase;
import com.universal.frame.pulltorefresh.PullToRefreshScrollView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import okhttp3.Request;

import static com.universal.frame.generalutils.DateUtil.starmpToData;

/**
 * Created by sa on 2018/7/31.
 */

public class UnpaidActivity extends BaseActivity implements ResultCallBack, AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener2 {
    private int page = 1;
    private UnpaidAdapter unpaidAdapter;
    private OrderDetailAdapter orderDetailAdapter;
    private NoScrollingListView nlv_unpaid;
    private NoScrollingListView nlv_shoplist;
    private List<UpaidBean> list = new ArrayList<UpaidBean>();
    private List<OrederBean> orderlist = new ArrayList<OrederBean>();
    private ImageView iv_erweima;
    private TextView tv_js_num, tv_yj, tv_yfj, tv_name, tv_time, tv_yfk, tv_ts;
    private PullToRefreshScrollView pull_refresh_scrollview;
    private PullToRefreshScrollView pull_refresh_scrollview2;
    private LinearLayout ll_top1;
    private boolean toRefresh = true;
    private Customer2Activity presentation;
    private Display[] presentationDisplays;
    private ComfirmPay2Dialog comfirmPayDialog;
    private ErW erweima;
    private String NUM;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_unpaid);
        DisplayManager displayManager = (DisplayManager) this.getSystemService(Context.DISPLAY_SERVICE);
        //获取屏幕数量
        presentationDisplays = displayManager.getDisplays();
        if (presentationDisplays.length > 1) {
            presentation = new Customer2Activity(this, presentationDisplays[1]);

        } else {
            presentation = new Customer2Activity(this, presentationDisplays[0]);
        }

        presentation.show();

    }

    @Override
    public void initView() {
        nlv_unpaid = (NoScrollingListView) findViewById(R.id.nlv_unpaid);
        nlv_shoplist = (NoScrollingListView) findViewById(R.id.nlv_shoplist);
        iv_erweima = (ImageView) findViewById(R.id.iv_erweima);
        ll_top1 = (LinearLayout) findViewById(R.id.ll_top1);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_time = (TextView) findViewById(R.id.tv_time);
        tv_js_num = (TextView) findViewById(R.id.tv_js_num);
        tv_yj = (TextView) findViewById(R.id.tv_yj);
        tv_yfj = (TextView) findViewById(R.id.tv_yfj);
        tv_yfk = (TextView) findViewById(R.id.tv_yfk);
        tv_ts = (TextView) findViewById(R.id.tv_ts);
        pull_refresh_scrollview = (PullToRefreshScrollView) findViewById(R.id.pull_refresh_scrollview);
        pull_refresh_scrollview2 = (PullToRefreshScrollView) findViewById(R.id.pull_refresh_scrollview2);
        initScrollView();
        initScrollView2();
        getListInfo(page);
//        gListInfo(page);
    }

    public void initScrollView() {
        this.pull_refresh_scrollview.getLoadingLayoutProxy(false, true)
                .setPullLabel(
                        this.getResources().getString(
                                R.string.pull_to_refresh_pull_label_up));
        pull_refresh_scrollview.getLoadingLayoutProxy(false, true)
                .setRefreshingLabel(
                        this.getResources().getString(
                                R.string.pull_to_refresh_refreshing_label));
        pull_refresh_scrollview.getLoadingLayoutProxy(false, true)
                .setReleaseLabel(
                        this.getResources().getString(
                                R.string.pull_to_refresh_release_label));

        pull_refresh_scrollview.setMode(PullToRefreshBase.Mode.BOTH);//both  可以上拉、可以下拉
        pull_refresh_scrollview.setOnRefreshListener(this);
        unpaidAdapter = new UnpaidAdapter(this, list);
        nlv_unpaid.setAdapter(unpaidAdapter);
        nlv_unpaid.setOnItemClickListener(this);

    }

    public void initScrollView2() {
        this.pull_refresh_scrollview2.getLoadingLayoutProxy(false, true)
                .setPullLabel(
                        this.getResources().getString(
                                R.string.pull_to_refresh_pull_label_up));
        pull_refresh_scrollview2.getLoadingLayoutProxy(false, true)
                .setRefreshingLabel(
                        this.getResources().getString(
                                R.string.pull_to_refresh_refreshing_label));
        pull_refresh_scrollview2.getLoadingLayoutProxy(false, true)
                .setReleaseLabel(
                        this.getResources().getString(
                                R.string.pull_to_refresh_release_label));

        pull_refresh_scrollview2.setMode(PullToRefreshBase.Mode.DISABLED);//both  可以上拉、可以下拉

        orderDetailAdapter = new OrderDetailAdapter(this, orderlist);
        nlv_shoplist.setAdapter(orderDetailAdapter);

    }

    //查看列表
    public void getListInfo(int page) {
        String userID = SharedPreferencesUtil.getString(this, ConstantsUtils.USER_ID);
        String warehouse = SharedPreferencesUtil.getString(this, ConstantsUtils.WAREHOUSE_ID);
        OKHttpUtils.postAsync(this
                , HttpAddress.SERVICE_LOCATION_ORDERLIST, userID
                , new RequestParams(this).getShopListParams(page,warehouse)
                , this
                , false, 1);
    }

    //查看订单支付二维码
    public void getErWeiMaInfo(String businessId, String businessNo, String customId, String amount) {
        String userID = SharedPreferencesUtil.getString(this, ConstantsUtils.USER_ID);
        OKHttpUtils.postAsync(this
                , HttpAddress.SERVICE_ERWEIMA, userID
                , new RequestParams(this).getErWeiMaParams(businessId, businessNo, customId, userID, amount)
                , this
                , false, 2);
    }

    //订单详情
    public void getOrderInfo(String keyid) {
        String userID = SharedPreferencesUtil.getString(this, ConstantsUtils.USER_ID);
        OKHttpUtils.postAsync(this
                , HttpAddress.SERVICE_ODDERDETAIL, userID
                , new RequestParams(this).getOrderParams(keyid)
                , this
                , false, 3);
    }
//    //查看商品详情
//    public void gListInfo(int page) {
//        String userID = SharedPreferencesUtil.getString(this, ConstantsUtils.USER_ID);
//        String wareID = SharedPreferencesUtil.getString(this, ConstantsUtils.WAREHOUSE_ID);
//        OKHttpUtils.postAsync(this
//                , HttpAddress.SERVICE_bendiLIST, ""
//                , new RequestParams(this).getbendiParams(page,wareID)
//                , this
//                , false, 4);
//    }
//    //订单详情
//    public void getOrderdddInfo(String keyid) {
//        String userID = SharedPreferencesUtil.getString(this, ConstantsUtils.USER_ID);
//        OKHttpUtils.postAsync(this
//                , HttpAddress.SERVICE_bendiLIST, userID
//                , new RequestParams(this).getOrderParams(keyid)
//                , this
//                , false, 5);
//    }
    @Override
    public void onSuccess(String response, int flag) {
        try {
            if (flag == 1) {
                getListData(response);
            }
            if (flag == 2) {
                getErWeiMaData(response);
            }
            if (flag == 3) {
                getOrderData(response);
            }
//            if (flag == 5) {
//                getbendiData(response);
//            }
        } catch (Exception e) {
            GeneralUtil.tryShow(getApplicationContext(), e);
        }
    }

    private void getbendiData(String response) {
        Log.i("lzx", "getbendiData: "+response);
    }


    private void getListData(String response) {
        ManageUpaidInfo info = JSON.parseObject(response, ManageUpaidInfo.class);
        if (info.list != null) {
            if (info.list.size() > 0) {

                if (page == 1) {
                    list.clear();
                    list.addAll(info.list);

                } else {
                    list.addAll(info.list);
                }
            } else {
                list.clear();
            }
            if (info.list.size() < 30) {
                toRefresh = false;
            } else {
                toRefresh = true;
            }
            unpaidAdapter.notifyDataSetChanged();
        }else {
            list.clear();
            unpaidAdapter.notifyDataSetChanged();
        }
    }

    private void getErWeiMaData(String response) {
        String check = JsonUtil.getString(response, "check", "");
        if ("1".equals(check)) {
            iv_erweima.setVisibility(View.VISIBLE);
            tv_ts.setVisibility(View.GONE);
            String image = JsonUtil.getString(response, "image", "");
            Glide.with(getApplicationContext()).load(erweima(image)).fitCenter().into(iv_erweima);
            erweima =JSON.parseObject(response,ErW.class);
            showWareHouse(NUM,erweima);
        } else {
            iv_erweima.setVisibility(View.GONE);
            tv_ts.setVisibility(View.VISIBLE);
            ToastUtil.showToast(this, "生成二维码失败");
        }
    }

    private void getOrderData(String response) {
        Log.i("lzx", "getOrderData: "+response);
//        String list = JsonUtil.getString(response, "list", "");
        ManageOrderInfo info = JSON.parseObject(response, ManageOrderInfo.class);
        if (info.list != null) {
            if (info.list.size() > 0) {
                ll_top1.setVisibility(View.VISIBLE);
                orderlist.clear();
                orderlist.addAll(info.list);
            } else {
                orderlist.clear();
                ll_top1.setVisibility(View.GONE);
            }
            orderDetailAdapter.notifyDataSetChanged();
            EventBus.getDefault().post(new UnpaidCustomerShopEvent(orderlist));
        }else {
            ll_top1.setVisibility(View.GONE);
            orderlist.clear();
            orderDetailAdapter.notifyDataSetChanged();
            EventBus.getDefault().post(new UnpaidCustomerShopEvent(orderlist));
        }
    }
    @Override
    public void onFailure(Request request, IOException e, int flag) {

    }

    private byte[] erweima(String base64) {
        Bitmap bitmap = null;
        byte[] bitmapArray;
        bitmapArray = Base64.decode(base64, Base64.DEFAULT);
        bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] bytes = baos.toByteArray();
        return bytes;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        getErWeiMaInfo(list.get(position).ID, list.get(position).PART_SALE_NO, list.get(position).SALE_CUST_ID, list.get(position).REMAINDER);
        getOrderInfo(list.get(position).ID);
        NUM = list.get(position).ID;
        String name = list.get(position).SALE_CUST_NAME;
        String YJ = list.get(position).SALE_AMOUNT;
        String YFK =list.get(position).REMAINDER;
        String YF =list.get(position).HAS_PAID;
        tv_name.setText(name);
        tv_time.setText(starmpToData(list.get(position).CREATE_DATE));
        tv_js_num.setText("8件");
        tv_yj.setText("￥" + YJ);
        tv_yfj.setText("￥" + YFK);
        tv_yfk.setText("￥" + YF);
        EventBus.getDefault().post(new UnpaidEvent(list.get(position).SALE_CUST_NAME,YJ,list.get(position).DISCOUNT_RATE,list.get(position).DISCOUNT_AMOUNT,YF,YFK));

    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        pull_refresh_scrollview.onRefreshComplete();
        page = 1;
        getListInfo(page);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        pull_refresh_scrollview.onRefreshComplete();
        if (toRefresh) {
            page++;
            getListInfo(page);
        } else {
            ToastUtil.showToast(this, "没有更多数据");
            pull_refresh_scrollview.onRefreshComplete();
        }
    }
    private void showWareHouse(String order_id,ErW erW) {
        comfirmPayDialog = new ComfirmPay2Dialog(this,order_id,erW, R.style.MyDialogStyle, new BaseDialog.LeaveMyDialogListener() {

            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.tv_close:
                        comfirmPayDialog.dismiss();
                        orderlist.clear();
                        orderDetailAdapter.notifyDataSetChanged();
                        iv_erweima.setVisibility(View.GONE);
                        ll_top1.setVisibility(View.GONE);
                        tv_name.setText("");
                        tv_time.setText("");
                        tv_yj.setText("￥0.00");
                        tv_yfj.setText("￥0.00");
                        tv_yfk.setText("￥0.00");
                        EventBus.getDefault().post(new UnpaidCustomerShopEvent(orderlist));
                        EventBus.getDefault().post(new UnpaidEvent("暂未获取","0.00","1","0.00","0.00","0.00"));
                        ToastUtil.showToast(getApplicationContext(), "订单尚未支付!", 2000);
                        break;
                    default:
                        break;
                }



                }

        });

        comfirmPayDialog.show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        presentation.dismiss();
    }
    @Override
    @Subscribe
    public void onEventMainThread(BaseEvent event) throws IOException {
        super.onEventMainThread(event);
       if (event instanceof PaystatrEvent) {
        if (((PaystatrEvent) event).getType() == 2) {
            ToastUtil.showToast(getApplicationContext(), "订单支付成功！", 3000);
            EventBus.getDefault().post(new PaySEvent(2));
            orderlist.clear();
            orderDetailAdapter.notifyDataSetChanged();
            iv_erweima.setVisibility(View.GONE);
            ll_top1.setVisibility(View.GONE);
            tv_name.setText("");
            tv_time.setText("");
            tv_yj.setText("￥0.00");
            tv_yfj.setText("￥0.00");
            tv_yfk.setText("￥0.00");
            EventBus.getDefault().post(new UnpaidCustomerShopEvent(orderlist));
            EventBus.getDefault().post(new UnpaidEvent("暂未获取","0.00","1","0.00","0.00","0.00"));
        }
    }
    }
}
